package com.data.modules.smzh.controller;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import com.data.common.api.vo.Result;
import com.data.common.system.query.QueryGenerator;
import com.data.common.util.ConvertUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.data.modules.smzh.entity.SmUser;
import com.data.modules.smzh.entity.SmzhCarLog;
import com.data.modules.smzh.entity.UserCard;
import com.data.modules.smzh.service.ISmUserService;
import com.data.modules.smzh.service.ISmzhCarLogService;
import com.data.modules.smzh.service.IUserCardService;
import lombok.extern.slf4j.Slf4j;

import org.apache.poi.ss.formula.functions.T;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import com.data.common.system.base.controller.BootController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import com.data.common.aspect.annotation.AutoLog;

 /**
 * @Description: 用户卡导入日志
 * @Author: data-boot
 * @Date:   2023-01-10
 * @Version: V1.0
 */
@Api(tags="用户卡导入日志")
@RestController
@RequestMapping("/smzh/smzhCarLog")
@Slf4j
public class SmzhCarLogController extends BootController<SmzhCarLog, ISmzhCarLogService> {
	@Autowired
	private ISmzhCarLogService smzhCarLogService;

	 @Autowired
	 private ISmUserService userService;

	 @Autowired
	 private IUserCardService userCardService;

	/**
	 * 分页列表查询
	 *
	 * @param smzhCarLog
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "用户卡导入日志-分页列表查询")
	@ApiOperation(value="用户卡导入日志-分页列表查询", notes="用户卡导入日志-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(SmzhCarLog smzhCarLog,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<SmzhCarLog> queryWrapper = QueryGenerator.initQueryWrapper(smzhCarLog, req.getParameterMap());
		Page<SmzhCarLog> page = new Page<SmzhCarLog>(pageNo, pageSize);
		IPage<SmzhCarLog> pageList = smzhCarLogService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	/**
	 *   添加
	 *
	 * @param smzhCarLog
	 * @return
	 */
	@AutoLog(value = "用户卡导入日志-添加")
	@ApiOperation(value="用户卡导入日志-添加", notes="用户卡导入日志-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody SmzhCarLog smzhCarLog) {
		smzhCarLogService.save(smzhCarLog);
		return Result.OK("添加成功！");
	}

	/**
	 *  编辑
	 *
	 * @param smzhCarLog
	 * @return
	 */
	@AutoLog(value = "用户卡导入日志-编辑")
	@ApiOperation(value="用户卡导入日志-编辑", notes="用户卡导入日志-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody SmzhCarLog smzhCarLog) {
		smzhCarLogService.updateById(smzhCarLog);
		return Result.OK("编辑成功!");
	}

	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "用户卡导入日志-通过id删除")
	@ApiOperation(value="用户卡导入日志-通过id删除", notes="用户卡导入日志-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		smzhCarLogService.removeById(id);
		return Result.OK("删除成功!");
	}

	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "用户卡导入日志-批量删除")
	@ApiOperation(value="用户卡导入日志-批量删除", notes="用户卡导入日志-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.smzhCarLogService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}

	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "用户卡导入日志-通过id查询")
	@ApiOperation(value="用户卡导入日志-通过id查询", notes="用户卡导入日志-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		SmzhCarLog smzhCarLog = smzhCarLogService.getById(id);
		if(smzhCarLog==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(smzhCarLog);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param smzhCarLog
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SmzhCarLog smzhCarLog) {
        return super.exportXls(request, smzhCarLog, SmzhCarLog.class, "用户卡导入日志");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
       // return super.importExcel(request, response, SmzhCarLog.class);

		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			//params.setTitleRows(2);
			//params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<SmzhCarLog> list = ExcelImportUtil.importExcel(file.getInputStream(), SmzhCarLog.class, params);
				long start = System.currentTimeMillis();

				if(ObjectUtil.isNotEmpty(list)){

					list.stream().forEach(x->{

						SmUser smUser = userService.lambdaQuery().eq(SmUser::getAppId,x.getAppId()).eq(SmUser::getPersonCode,x.getPersonCode())
								.eq(SmUser::getPersonId,x.getPersonId()).eq(SmUser::getPersonName,x.getPersonName()).one();
						if(ObjectUtil.isNotEmpty(smUser)){

							x.setUserId(String.valueOf(smUser.getId()));

							//根据userid 删除 卡信息
							userCardService.deleteByUserId(smUser.getId());

							UserCard userCard = new UserCard();
							userCard.setUserId(smUser.getId());
							userCard.setCardNumber(x.getCardNumber());
							userCard.setCardType(1);

							userCardService.save(userCard);

							x.setResult(1);
						}else{
							x.setResult(2);
						}

					});

				}

				smzhCarLogService.saveBatch(list);
				//400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				//1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				//update-end-author:data-boot date:20190528 for:批量插入数据
				return Result.ok("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
	}


}
